<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑节点"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="left"
    >
      <el-form-item label="节点名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="支持1~20字符"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="审批人类型" prop="approverType">
        <el-select
          v-model="formData.approverType"
          placeholder="请选择审批人类型"
          style="width: 100%"
          @change="handleApproverTypeChange"
        >
          <el-option label="指定用户" value="user" />
          <el-option label="指定角色" value="role" />
          <el-option label="指定部门" value="department" />
        </el-select>
      </el-form-item>

      <!-- 指定角色 -->
      <template v-if="formData.approverType === 'role'">
        <el-form-item label="审批角色" prop="approverRole">
          <el-select
            v-model="formData.approverRole"
            placeholder="请选择审批角色"
            style="width: 100%"
            filterable
            @change="handleRoleChange"
          >
            <el-option
              v-for="role in enabledRoles"
              :key="role.id"
              :label="role.roleName"
              :value="role.roleName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批用户">
          <el-select
            v-model="formData.approverUsers"
            placeholder="请选择审批用户"
            style="width: 100%"
            multiple
            filterable
            :disabled="!formData.approverRole"
            @focus="loadRoleUsers"
          >
            <el-option
              v-for="user in roleUsers"
              :key="user.userId"
              :label="`${user.nickName}(${user.userName})`"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </template>

      <!-- 指定用户 -->
      <template v-if="formData.approverType === 'user'">
        <el-form-item label="审批用户" prop="approverUsers">
          <el-select
            v-model="formData.approverUsers"
            placeholder="请选择审批用户"
            style="width: 100%"
            multiple
            filterable
            @focus="loadAllUsers"
          >
            <el-option
              v-for="user in allUsers"
              :key="user.userId"
              :label="`${user.nickName}(${user.userName})`"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </template>

      <!-- 指定部门 -->
      <template v-if="formData.approverType === 'department'">
        <el-form-item label="审批组织" prop="approverDepartment">
          <el-tree-select
            v-model="formData.approverDepartment"
            :data="departmentTree"
            placeholder="请选择审批组织"
            style="width: 100%"
            :props="treeProps"
            filterable
            @change="handleDepartmentChange"
          />
        </el-form-item>

        <el-form-item label="审批用户">
          <el-select
            v-model="formData.approverUsers"
            placeholder="请选择审批用户"
            style="width: 100%"
            multiple
            filterable
            :disabled="!formData.approverDepartment"
            @focus="loadDepartmentUsers"
          >
            <el-option
              v-for="user in departmentUsers"
              :key="user.userId"
              :label="`${user.nickName}(${user.userName})`"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  nodeData: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['update:visible', 'confirm'])

// 响应式数据
const dialogVisible = ref(false)
const formRef = ref()

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  approverType: 'user',
  approverRole: '',
  approverDepartment: '',
  approverUsers: []
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入节点名称', trigger: 'blur' },
    { min: 1, max: 20, message: '节点名称长度为1-20个字符', trigger: 'blur' }
  ],
  approverType: [{ required: true, message: '请选择审批人类型', trigger: 'change' }],
  approverRole: [{ required: true, message: '请选择审批角色', trigger: 'change' }],
  approverDepartment: [{ required: true, message: '请选择审批组织', trigger: 'change' }],
  approverUsers: [{ required: true, message: '请选择审批用户', trigger: 'change' }]
}

// 数据源
const enabledRoles = ref([])
const roleUsers = ref([])
const allUsers = ref([])
const departmentUsers = ref([])
const departmentTree = ref([])

// 树形选择器配置
const treeProps = {
  label: 'label',
  value: 'id',
  children: 'children'
}

// 监听visible变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
    if (newVal) {
      initFormData()
      loadBaseData()
    }
  }
)

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

/** 初始化表单数据 */
const initFormData = () => {
  const data = props.nodeData
  formData.id = data.id || null
  formData.name = data.name || ''
  formData.approverType = data.approverType || 'user'
  formData.approverRole = data.approverRole || ''
  formData.approverDepartment = data.approverDepartment || ''
  formData.approverUsers = data.approverUsers || []
}

/** 加载基础数据 */
const loadBaseData = async () => {
  await Promise.all([loadEnabledRoles(), loadAllUsers(), loadDepartmentTree()])
}

/** 加载启用的角色 */
const loadEnabledRoles = async () => {
  // 模拟API调用
  setTimeout(() => {
    enabledRoles.value = [
      { id: 1, roleName: '启用的角色A', status: '0' },
      { id: 2, roleName: '启用的角色B', status: '0' },
      { id: 3, roleName: '财务负责人', status: '0' },
      { id: 4, roleName: '技术负责人', status: '0' }
    ]
  }, 100)
}

/** 加载所有用户 */
const loadAllUsers = async () => {
  // 模拟API调用
  setTimeout(() => {
    allUsers.value = [
      { userId: 1, userName: 'zhangsan', nickName: '张三', deptId: 1 },
      { userId: 2, userName: 'lisi', nickName: '李四', deptId: 2 },
      { userId: 3, userName: 'wangwu', nickName: '王五', deptId: 1 },
      { userId: 4, userName: 'zhaoliu', nickName: '赵六', deptId: 3 }
    ]
  }, 100)
}

/** 加载部门树 */
const loadDepartmentTree = async () => {
  // 模拟API调用
  setTimeout(() => {
    departmentTree.value = [
      {
        id: 1,
        label: '公司名称',
        children: [
          {
            id: 2,
            label: '部门A',
            children: [
              {
                id: 3,
                label: '小组A'
              },
              {
                id: 4,
                label: '小组B'
              }
            ]
          },
          {
            id: 5,
            label: '部门B'
          },
          {
            id: 6,
            label: '部门C'
          }
        ]
      }
    ]
  }, 100)
}

/** 加载角色用户 */
const loadRoleUsers = async () => {
  if (!formData.approverRole) return

  // 模拟API调用
  setTimeout(() => {
    roleUsers.value = [
      { userId: 1, userName: 'zhangsan', nickName: '张三' },
      { userId: 2, userName: 'lisi', nickName: '李四' }
    ]
  }, 100)
}

/** 加载部门用户 */
const loadDepartmentUsers = async () => {
  if (!formData.approverDepartment) return

  // 模拟API调用
  setTimeout(() => {
    departmentUsers.value = [
      { userId: 1, userName: 'zhangsan', nickName: '张三' },
      { userId: 3, userName: 'wangwu', nickName: '王五' }
    ]
  }, 100)
}

/** 审批人类型变化 */
const handleApproverTypeChange = () => {
  // 清空相关字段
  formData.approverRole = ''
  formData.approverDepartment = ''
  formData.approverUsers = []
}

/** 角色变化 */
const handleRoleChange = () => {
  formData.approverUsers = []
  if (formData.approverRole) {
    loadRoleUsers()
  }
}

/** 部门变化 */
const handleDepartmentChange = () => {
  formData.approverUsers = []
  if (formData.approverDepartment) {
    loadDepartmentUsers()
  }
}

/** 关闭弹窗 */
const handleClose = () => {
  dialogVisible.value = false
}

/** 确认操作 */
const handleConfirm = async () => {
  try {
    await formRef.value.validate()

    // 验证审批人配置
    if (formData.approverType === 'role' && !formData.approverRole) {
      ElMessage.warning('请选择审批角色')
      return
    }

    if (formData.approverType === 'department' && !formData.approverDepartment) {
      ElMessage.warning('请选择审批组织')
      return
    }

    if (!formData.approverUsers || formData.approverUsers.length === 0) {
      ElMessage.warning('请选择至少一个审批用户')
      return
    }

    emit('confirm', { ...formData })
    dialogVisible.value = false
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-tree-select) {
  width: 100%;
}
</style>
